package logparser.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.sql.Time;

import logparser.AppConfig;
import logparser.bean.ParserControl;
import logparser.bean.ParserNearbyFootball;
import logparser.bean.ParserSystem;
import logparser.ui.LogcatMonitor;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Label;

public class Main {

	protected Shell shell;
	private Text text;
	private File logcatFile;
	private String outputFolder;
	private Text text_status;
	
	
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Main window = new Main();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell(SWT.CLOSE | SWT.MIN | SWT.TITLE);
		shell.setSize(579, 392);
		shell.setText("Android Logcat Parser");
		
		AppConfig.getInstance().loadConfig();
		
		text = new Text(shell, SWT.BORDER | SWT.READ_ONLY);
		text.setBounds(13, 29, 381, 21);
		text.setText(AppConfig.getInstance().getLogcatPath());
		logcatFile = new File(AppConfig.getInstance().getLogcatPath());
		
		
		
		Button btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				File log_file = UIUtils.showFileDialog(shell,new String[]{"*.log","*.*"});
				text.setText(log_file.getAbsolutePath());
				logcatFile = log_file;
			}
		});
		btnNewButton.setBounds(400, 27, 163, 25);
		btnNewButton.setText("Select Logcat File");
		
		Button btnNewButton_1 = new Button(shell, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(logcatFile == null){
					UIUtils.showErrorMessageBox(shell,"Please select logcat file");
					return;
				}
				
				if(!logcatFile.exists()){
					UIUtils.showErrorMessageBox(shell,"File:" + logcatFile.getAbsolutePath() + " not exist,please check");
					return;
				}
				
				AppConfig.getInstance().setLogcatPath(logcatFile.getAbsolutePath());
				AppConfig.getInstance().saveConfig();
				processFolder();
				text_status.setText("Starting process....\n");
				text_status.update();
				long time = System.currentTimeMillis();
				if(processLogcat()){
					UIUtils.showMessageBox(shell,"Done!!");
					long during = (System.currentTimeMillis() - time)/1000;
					text_status.append("Done,the output path is " + outputFolder);
					text_status.append("\nTotal seconds:" + during);
				}else{
					text_status.append("got some errors");
				}
				
				
			}
		});
		btnNewButton_1.setBounds(13, 87, 550, 25);
		btnNewButton_1.setText("Parse");
		
		Button btnNewButton_2 = new Button(shell, SWT.NONE);
		btnNewButton_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				new LogcatMonitor(shell).open();
			}
		});
		btnNewButton_2.setBounds(13, 142, 550, 25);
		btnNewButton_2.setText("Start LogcatMontor");
		
		text_status = new Text(shell, SWT.BORDER | SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
		text_status.setEditable(false);
		text_status.setBounds(10, 210, 553, 148);
		
		Label lblOutput = new Label(shell, SWT.NONE);
		lblOutput.setBounds(10, 181, 55, 15);
		lblOutput.setText("output");
		
	}
	
	private boolean processLogcat(){
		String line;
		InputStream fis;

		try {
			fis = new FileInputStream(logcatFile);
		    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
		    BufferedReader br = new BufferedReader(isr);
		    ParserControl.getInstance().setOutputFolder(outputFolder);
		    ParserControl.getInstance().processStart();
		    int lineNum = 0;
		    
		    while ((line = br.readLine()) != null) {
		        // Deal with the line
		    	lineNum++;
		    	//System.out.println("Processing " + lineNum);
		    	ParserControl.getInstance().processLine(line, lineNum);
		    }
		    fis.close();
		}catch (Exception e){
			e.printStackTrace();
			UIUtils.showErrorMessageBox(shell,e.getMessage());
			return false;
		}
		
		ParserControl.getInstance().processEnd();
		
//		try {
//			Runtime.getRuntime().exec("explorer.exe " + outputFolder);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		return true;
	}
	
	private void processFolder(){
		outputFolder = logcatFile.getPath() + ".output";
	}
	
	

	
}
